import sys
from PIL import ImageFont, ImageDraw ,Image


with open(f"out/data.csv", "w") as text_file:
    # loop through command line arguments
    for i in range(1, len(sys.argv)):
        # create new image
        image = Image.new(mode="1", size=(72, 40), color=0)
        draw = ImageDraw.Draw(image)

        # use a truetype font
        font = ImageFont.truetype("DroidSansFallback.ttf", 24)

        # get text size
        text_width, text_height = draw.textsize(sys.argv[i], font=font)

        # calculate x, y position of text
        x = (image.width - text_width) // 2
        y = (image.height - text_height) // 2

        # draw text in white color
        draw.text((x, y), sys.argv[i], font=font, fill=1)

        # save image with filename as argument string
        image.save(f"out/{sys.argv[i]}.bmp", quality=95)

        # 打开 BMP 文件
        with Image.open(f"out/{sys.argv[i]}.bmp") as img:
            # 获取图像的宽度和高度
            width, height = img.size

            print("width:{},height:{}",width,height)

            # 获取像素数据
            pixels = img.load()

            bmp_bitmap_data=""
            compatPixels=[]

            # 遍历图像的每一个像素
            for y in range(int(height/8)):
                line=[]
                for x in range(width):
                    
                    bit0= 0 if pixels[x, y*8] == 255 else 1
                    bit1= 0 if pixels[x, y*8+1] == 255 else 1
                    bit2= 0 if pixels[x, y*8+2] == 255 else 1
                    bit3= 0 if pixels[x, y*8+3] == 255 else 1
                    bit4= 0 if pixels[x, y*8+4] == 255 else 1
                    bit5= 0 if pixels[x, y*8+5] == 255 else 1
                    bit6= 0 if pixels[x, y*8+6] == 255 else 1
                    bit7= 0 if pixels[x, y*8+7] == 255 else 1
                    num=bit7*128 + bit6*64 + bit5*32 + bit4*16 + bit3*8 + bit2*4 + bit1*2 + bit0
                    # print("x:{},y:{},num:{}",x,y,num)
                    line.append(num)
                compatPixels.append(line)
            
            print(compatPixels)
            cnt=0
            # 遍历图像的每一个像素
            for y in range(int(height/8)):
                for x in range(width):
                    # 获取像素值
                    str=hex(compatPixels[y][x]).upper()
                    # print("x:{},y:{},str:{}",x,y,compatPixels[y][x])
                    # str=",".join([f"0x{byte:02X}" pixels[x, y] ])
                    bmp_bitmap_data += str
                    bmp_bitmap_data += ","
                    cnt += 1
                    if cnt % 16 == 0 and cnt != 0:
                        bmp_bitmap_data += "\n"
                    
            text_file.write(bmp_bitmap_data)
            text_file.write("\n")


